package com.yangtao.prototype.system.menu.web;

import com.yangtao.framework.common.AjaxResult;
import com.yangtao.framework.common.Message;
import com.yangtao.framework.common.SystemConstant;
import com.yangtao.framework.web.struts2.BaseAction;
import com.yangtao.prototype.system.menu.service.MenuService;

import java.util.HashMap;
import java.util.Map;

public class MenuAction extends BaseAction<MenuModel, MenuService> {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * 菜单管理界面初始化
	 *
	 * @return
	 */
	public String init() {
		model = service.loadMenuTree(model);
		return render("MenuTree");
	}

//    /**
//     * 加载菜单树
//     *
//     * @return
//     */
//    public String loadMenuTree() {
//        model = service.loadMenuTree(model);
//        DojoDataModel dojoDataModel = new DojoDataModel();
//        dojoDataModel.setItems(model.getMenuTreeStore());
//        Struts2Utils.renderJson(dojoDataModel, true);
//        return null;
//    }

	/**
	 * 增加一个子菜单
	 *
	 * @return
	 */
	public String add() {
		model = service.addMenu(model);
//		if(hasError()){
//
//		}
//		AjaxResult result = new AjaxResult();
//		result.setState(SystemConstant.ERROR);
		Map<String, Object> returnJson = new HashMap<String, Object>();
		returnJson.put("id", model.getMenu().getId());
		returnJson.put("name", model.getMenu().getName());
		returnJson.put("level", model.getMenu().getLevel());
		returnJson.put("icon", model.getMenu().getIcon());
		return renderJson(returnJson);
	}

	/**
	 * 加载一个菜单信息
	 *
	 * @return
	 */
	public String load() {
		if ("add".equals(model.getProcessType())) {
			return render("MenuAdd");
		}
		if ("update".equals(model.getProcessType())) {
			model = service.loadMenu(model);
			return render("MenuUpdate");
		}
		return null;
	}

	/**
	 * 更新一个菜单信息
	 *
	 * @return
	 */
	public String save() {
		model = service.updateMenu(model);
		Map<String, Object> returnJson = new HashMap<String, Object>();
		if (hasError()) {
			returnJson.put("state", "error");
		} else {
			returnJson.put("state", "success");
		}
		StringBuilder message = new StringBuilder();
		if (model.getMessage() != null && model.getMessage().size() > 0) {
			for (Message m : model.getMessage()) {
				message.append("\n");
				String text = getText(m.getKey(), m.getArgs());
				message.append(text == null ? "" : text);
			}
		}
		returnJson.put("message", message.length() > 0 ? message.delete(0, 1).toString() : "");
		returnJson.put("id", model.getMenu().getId());
		returnJson.put("name", model.getMenu().getName());
		returnJson.put("level", model.getMenu().getLevel());
		returnJson.put("icon", model.getMenu().getIcon());
		return renderJson(returnJson);
	}

	/**
	 * 删除一个菜单
	 *
	 * @return
	 */
	public String delete() {
		model = service.deleteMenu(model);
		return renderJsonMessage();
	}
}
